package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItemParser;
import cc.eddic.practice.concurrency.LogParser;
import cc.eddic.practice.concurrency.LogItem;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
@Qualifier("LogParserWithLoopImpl")
public class LogParserWithLoopImpl implements LogParser {

    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String, List<LogItem>> result = new HashMap<>();
        try {
            val p = Paths.get(folderName);

            try (val walk = Files.walk(p)) {
                walk.parallel().filter(Files::isRegularFile)
//                        .filter(x -> x.getFileName().toString().startsWith("2023"))
                        .filter(x-> x.getFileName().toString().endsWith(".log"))
                        .forEach(path -> {
                            try (val lines = Files.lines(path)) {
                                val items = lines.map(logItemParser::parse).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
                                result.put(path.getFileName().toString(), items);
                            } catch (IOException ex) {
                                log.error(ex.getMessage(), ex);
                            }
                        });
            }
        } catch (IOException e) {
            log.error("File does not exists : {}", e.getMessage());
        }
        return result;
    }

    public LogParserWithLoopImpl(LogItemParser logItemParser) {
        this.logItemParser = logItemParser;
    }

    private final LogItemParser logItemParser;
}
